import React, { useMemo, useState, Fragment } from 'react';
import Cls from 'classnames';
import { Button, Divider, Form, Space } from 'antd';

import './style.less';
import componentMap from './ComponentMap';
import { arabicToChinese, onMouseOutBtn, priceFormat } from '@/utils';
import { DescriptionsTypeAPI } from '../src/type';
import { TypographyTitle } from '@/components/Typography';
import { isNumber } from 'lodash';

/**
 * @getLabelStyle 生成label宽度
 * @param value 宽度
 * @returns
 */
const getLabelStyle = (value: number | undefined, oaType: boolean | any) => {
  let styObj = {
    width: `${value}px`,
    minWidth: `${value}px`,
  };
  if (oaType) {
    styObj['backgroundColor'] = '#f2f6fc63';
  }
  return styObj;
};

/**
 * @getContentlStyle 生成内容宽度
 * @param value  宽度
 * @returns
 */
const getContentlStyle = (value: number | undefined) => {
  return {
    width: `calc(100% - ${value}px)`,
  };
};

const DescriptionsType: React.FC<DescriptionsTypeAPI.IDescriptionsTypePop> = ({ config, titleType, ...otherFuncApi }) => {
  const { form, name, dataSource, labelWidth, headerSchema, disabled, isShowNumTitle } = config;

  const [_, setFormData] = useState({});

  const descriptionData: DescriptionsTypeAPI.IFormProps[] = useMemo(() => {
    return dataSource || [];
  }, [dataSource]);

  const contentRender = (item: any) => {
    const {
      field,
      required = false,
      slotRender,
      render,
      label,
      messageTrue,
      message = `请输入${label}`,
      placeholder = `请输入${label}`,
      component,
      contentAfter = null,
      pattern,
      patternMsg,
      dependencies,
      rules,
    } = item;

    // 根据component获取对应控件
    const Comp = componentMap.get(component);
    // 判断slotRender 是否为函数
    const isSlotRender = slotRender && typeof slotRender == 'function';

    const itemValue = form.getFieldValue(field);
    const recordValue = form.getFieldsValue();

    const props = {
      disabled: disabled,
      placeholder,
      ...item,
    };

    // DOM元素删除不识别属性
    delete props['initialValue'];
    delete props['contentAfter'];
    delete props['defaultValue'];
    delete props['ishidden'];
    delete props['pattern'];
    delete props['patternMsg'];
    delete props['messageTrue'];

    /** 处理必传和正则 */
    let rulesInfoList: Record<string, any>[] = [
      {
        required: required,
        message: messageTrue || message,
      },
    ];
    if (pattern) {
      rulesInfoList?.push({
        pattern: pattern,
        message: patternMsg,
      });
    }

    if (rules) {
      rulesInfoList = [...rulesInfoList, ...rules];
    }

    return (
      <Fragment>
        {isSlotRender ? (
          slotRender(itemValue, recordValue)
        ) : render && typeof render == 'function' ? (
          <>
            <Form.Item
              name={field}
              rules={rulesInfoList}
              initialValue={item?.initialValue}
              shouldUpdate={(_, value) => {
                setFormData(value);
                return true;
              }}
              dependencies={dependencies}
            >
              {render(itemValue, recordValue)}
            </Form.Item>
            {contentAfter != null && <div className="descriptionsType-item-content-anticon">{contentAfter}</div>}
          </>
        ) : (
          <>
            <Form.Item
              name={field}
              // rules={[{ required: required, message: message }]}
              rules={rulesInfoList}
              initialValue={item?.initialValue}
              dependencies={dependencies}
              shouldUpdate={(_, value) => {
                if (item.disabled && field == 'sumInTax' && isNumber(value.sumInTax)) {
                  value.sumInTax = priceFormat(value.sumInTax);
                }
                setFormData(value);
                return true;
              }}
            >
              <Comp {...props} />
            </Form.Item>
            {contentAfter != null && <div className="descriptionsType-item-content-anticon">{contentAfter}</div>}
          </>
        )}
      </Fragment>
    );
  };

  const headerRender = (headerSchema: DescriptionsTypeAPI.FormSchema) => {
    const Comp = componentMap.get(headerSchema.component);
    const props = {
      ...headerSchema,
    };
    // DOM元素删除不识别属性
    delete props['initialValue'];
    return (
      <div className={'descriptionsType-container-header'}>
        <Form.Item
          name={headerSchema.field}
          rules={[{ required: headerSchema.required, message: headerSchema?.message ?? `请输入${headerSchema.label}` }]}
          initialValue={headerSchema?.initialValue}
        >
          <Comp {...props} />
        </Form.Item>
      </div>
    );
  };

  const rowRender = (items: DescriptionsTypeAPI.FormSchema[], index: number) => {
    return (
      <div className={'descriptionsType-item-row'} key={index}>
        {items.map((item) => {
          const styleInfo: Record<string, any> = {};
          if (item?.display) {
            styleInfo['display'] = item?.display;
          }

          return (
            <div style={{ ...styleInfo }} className={Cls('descriptionsType-item', `descriptionsType-item-col-span-${item.colSpan ?? 1}`)} key={item.field}>
              <div className={'descriptionsType-item-label'} style={getLabelStyle(labelWidth, titleType)}>
                <span className={item.required ? 'required' : ''}>{item.label}</span>
              </div>
              <div className={'descriptionsType-item-content'} style={getContentlStyle(labelWidth)}>
                {contentRender(item)}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  return (
    <>
      {descriptionData.length > 0 && (
        <Form form={form} name={name} key={name} {...otherFuncApi}>
          <div className="descriptionsType-rootBoxDiv">
            {Object.keys(headerSchema as DescriptionsTypeAPI.FormSchema).length !== 0 && headerRender(headerSchema as DescriptionsTypeAPI.FormSchema)}
            {descriptionData.map((items: any, indexs: any) => {
              const itemIndex: string = arabicToChinese(indexs + 1);
              return (
                <Fragment key={items?.key}>
                  {items?.title && (
                    <>
                      {titleType ? (
                        <div
                          className="descriptionsType-rootBoxDiv-formTableTitleTypography"
                          style={{ display: 'flex', justifyContent: 'center', position: 'relative' }}
                        >
                          <TypographyTitle>
                            <span style={{ flex: 'auto' }}>
                              {isShowNumTitle && itemIndex + '、'}
                              {items?.titleText || '--'}
                            </span>
                            {items?.titleAfter && <span style={{ position: 'absolute', right: '0px' }}>{items?.titleAfter || ''}</span>}
                          </TypographyTitle>
                        </div>
                      ) : (
                        <div className="descriptionsType-rootBoxDiv-formTableTitle" style={{ display: 'flex', justifyContent: 'center' }}>
                          <span style={{ flex: 'auto' }}>
                            {isShowNumTitle && itemIndex + '、'}
                            {items?.title}
                          </span>
                          {items?.titleAfter || ''}
                        </div>
                      )}
                      {/* 头部操作按钮 */}
                      {items?.titleBtns?.length > 0 && (
                        <Space style={{ justifyContent: 'flex-end' }}>
                          {items?.titleBtns?.map((itemBtn: any, indexBtn: number) => {
                            if (itemBtn?.visible) {
                              return (
                                <Fragment key={`titleBtn-${indexBtn}`}>
                                  <Button
                                    type={itemBtn?.type}
                                    disabled={itemBtn?.disabled}
                                    size={itemBtn?.size}
                                    loading={itemBtn?.loading}
                                    icon={itemBtn?.icon}
                                    onClick={itemBtn?.onClick}
                                    onMouseOut={onMouseOutBtn}
                                  >
                                    {itemBtn?.title}
                                  </Button>
                                </Fragment>
                              );
                            } else {
                              return <></>;
                            }
                          })}
                        </Space>
                      )}
                    </>
                  )}
                  {items?.fieldCustomDom && <>{items?.fieldCustomDom}</>}

                  {items?.fieldChildren?.length > 0 && (
                    <div className="descriptionsType-container" key={`formItem-${indexs}`}>
                      {items?.fieldChildren?.map((itemChirden: any, indexChildren: number) => {
                        return rowRender(itemChirden, indexChildren);
                      })}
                    </div>
                  )}
                </Fragment>
              );
            })}
          </div>
        </Form>
      )}
    </>
  );
};

export default DescriptionsType;
